package com.ljkj.zjf.rest;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import com.ljkj.common.db.util.SecurityCode;
import com.ljkj.common.db.util.SecurityImage;
import com.ljkj.zjf.common.CacheManager;

@Path("rest/download")
public class SecurityCodeResource {

	@GET 
	@Path("/file") 
	@Produces(MediaType.APPLICATION_OCTET_STREAM) 
	public void serverLogDownload(@Context HttpServletResponse response){ 
		
		String securityCode = SecurityCode.getSecurityCode();
		try {
			//把"imgCode"放入到session中，生成的值是验证码值
			//验证验证码时，只需要验证imgCode的值是什么就可以了。
			CacheManager.getSession().put("imgCode", securityCode);
			//CacheManager.getSession().get(securityCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		InputStream imageStream = SecurityImage.getImageAsInputStream(securityCode);
		
		response.reset(); 
		response.setContentType("APPLICATION/OCTET-STREAM"); 
		
		try{
			ServletOutputStream out = response.getOutputStream(); 
			byte[] b = new byte[1024]; 
			int len; 
			while((len=imageStream.read(b)) >0){
				out.write(b,0,len); 
			}
			response.setStatus( response.SC_OK ); 
			response.flushBuffer(); 
			out.close(); 
			imageStream.close(); 
		}catch(IOException ex){
			ex.printStackTrace();
		}
		
	} 

}
